<template>
  <view class="create-bottle-page">
    <view class="page-header">
      <text class="header-title">写下你的心事</text>
      <button 
        class="post-button" 
        :disabled="!canPost"
        @click="handlePost"
      >
        投递
      </button>
    </view>

    <!-- 瓶子类型选择 -->
    <view class="bottle-type-selector">
      <view 
        class="type-card" 
        :class="{ active: selectedType === 'public' }"
        @click="selectType('public')"
      >
        <view class="type-card-title">公开漂流瓶</view>
        <view class="type-card-desc">投给陌生的有缘人</view>
      </view>
      <view 
        class="type-card" 
        :class="{ active: selectedType === 'private' }"
        @click="selectType('private')"
      >
        <view class="type-card-title">时光瓶</view>
        <view class="type-card-desc">写给未来的自己</view>
      </view>
    </view>

    <!-- 动态选项 -->
    <view class="options-container">
      <!-- 匿名选项 (公开瓶显示) -->
      <view 
        class="option-item" 
        v-if="selectedType === 'public'"
      >
        <text>匿名投递</text>
        <switch 
          :checked="isAnonymous"
          @change="handleAnonymousChange"
          color="#FFD700"
        />
      </view>
      
      <!-- 时间选择 (时光瓶显示) -->
      <view 
        class="option-item" 
        v-if="selectedType === 'private'"
      >
        <text>开启时间</text>
        <picker 
          mode="datetime" 
          :start="minDateTime"
          :end="maxDateTime"
          :value="openTime"
          @change="handleTimeChange"
        >
          <view class="time-picker">
            {{ displayTime || '选择时间' }}
          </view>
        </picker>
      </view>
    </view>

    <!-- 内容编辑器 -->
    <view class="content-editor">
      <textarea 
        class="text-area" 
        v-model="content"
        placeholder="在这里输入你的故事..."
        :maxlength="1000"
        @input="handleContentInput"
      />
      <view class="char-counter">{{ contentLength }} / 1000</view>
    </view>

    <!-- 成功提示覆盖层 -->
    <view 
      class="success-overlay" 
      :class="{ visible: showSuccess }"
    >
      <text>瓶子已成功投出！</text>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/store/user'
import { useBottleStore } from '@/store/bottle'
import dayjs from 'dayjs'

export default {
  name: 'CreateBottlePage',
  data() {
    return {
      selectedType: null,
      isAnonymous: false,
      openTime: '',
      content: '',
      showSuccess: false,
      isPosting: false
    }
  },
  
  computed: {
    userStore() {
      return useUserStore()
    },
    
    bottleStore() {
      return useBottleStore()
    },
    
    /**
     * 内容长度
     */
    contentLength() {
      return this.content.length
    },
    
    /**
     * 是否可以投递
     */
    canPost() {
      const hasContent = this.content.trim().length > 0
      const hasType = this.selectedType !== null
      
      if (!hasContent || !hasType) {
        return false
      }
      
      // 如果是时光瓶，必须选择时间
      if (this.selectedType === 'private') {
        return this.openTime !== ''
      }
      
      return true
    },
    
    /**
     * 最小时间（明天）
     */
    minDateTime() {
      return dayjs().add(1, 'day').format('YYYY-MM-DD HH:mm')
    },
    
    /**
     * 最大时间（10年后）
     */
    maxDateTime() {
      return dayjs().add(10, 'year').format('YYYY-MM-DD HH:mm')
    },
    
    /**
     * 显示时间
     */
    displayTime() {
      if (!this.openTime) return ''
      return dayjs(this.openTime).format('YYYY-MM-DD HH:mm')
    }
  },
  
  onLoad() {
    console.log('创建瓶子页面加载')
    this.initPage()
  },
  
  methods: {
    /**
     * 初始化页面
     */
    initPage() {
      // 检查是否可以投递
      if (!this.userStore.canSendBottle) {
        uni.showToast({
          title: '今日投递次数已用完',
          icon: 'none'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },
    
    /**
     * 选择瓶子类型
     */
    selectType(type) {
      this.selectedType = type
      
      // 重置相关选项
      if (type === 'public') {
        this.openTime = ''
      } else if (type === 'private') {
        this.isAnonymous = false
      }
    },
    
    /**
     * 处理匿名选项变化
     */
    handleAnonymousChange(event) {
      this.isAnonymous = event.detail.value
    },
    
    /**
     * 处理时间选择变化
     */
    handleTimeChange(event) {
      this.openTime = event.detail.value
    },
    
    /**
     * 处理内容输入
     */
    handleContentInput(event) {
      this.content = event.detail.value
    },
    
    /**
     * 处理投递
     */
    async handlePost() {
      if (!this.canPost || this.isPosting) {
        return
      }
      
      this.isPosting = true
      
      try {
        // 验证时间（时光瓶）
        if (this.selectedType === 'private') {
          const selectedTime = dayjs(this.openTime)
          const now = dayjs()
          
          if (selectedTime.isBefore(now.add(1, 'day'))) {
            uni.showToast({
              title: '开启时间至少为明天',
              icon: 'none'
            })
            return
          }
        }
        
        // 准备数据
        const bottleData = {
          type: this.selectedType,
          content: this.content,
          isAnonymous: this.isAnonymous,
          openTime: this.selectedType === 'private' ? this.openTime : null
        }
        
        // 创建瓶子
        const result = await this.bottleStore.createBottle(bottleData)
        
        if (result.success) {
          // 增加投递次数
          this.userStore.incrementSentCount()
          
          // 显示成功动画
          this.showSuccess = true
          
          // 延迟返回
          setTimeout(() => {
            uni.navigateBack()
          }, 2000)
        } else {
          uni.showToast({
            title: result.message || '投递失败',
            icon: 'error'
          })
        }
      } catch (error) {
        console.error('投递瓶子失败:', error)
        uni.showToast({
          title: '投递失败',
          icon: 'error'
        })
      } finally {
        this.isPosting = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.create-bottle-page {
  min-height: 100vh;
  background-color: var(--lighter-bg);
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  
  .header-title {
    font-size: 36rpx;
    font-weight: 500;
    color: var(--text-light);
  }
  
  .post-button {
    background-color: var(--accent-gold);
    color: var(--primary-bg);
    border: none;
    padding: 16rpx 40rpx;
    border-radius: 40rpx;
    font-weight: 500;
    font-size: 28rpx;
    transition: all 0.3s ease;
    
    &:disabled {
      background-color: var(--text-dark);
      color: #aaa;
    }
    
    &:not(:disabled):active {
      transform: scale(0.95);
    }
  }
}

.bottle-type-selector {
  display: flex;
  gap: 30rpx;
  margin-bottom: 40rpx;
  
  .type-card {
    flex: 1;
    padding: 30rpx;
    border: 4rpx solid var(--text-dark);
    border-radius: 24rpx;
    text-align: center;
    transition: all 0.3s ease;
    
    &.active {
      border-color: var(--accent-gold);
      background-color: rgba(255, 215, 0, 0.1);
      transform: translateY(-4rpx);
      box-shadow: 0 8rpx 20rpx rgba(255, 215, 0, 0.2);
    }
    
    .type-card-title {
      font-size: 32rpx;
      font-weight: 500;
      color: var(--text-light);
      margin-bottom: 10rpx;
    }
    
    .type-card-desc {
      font-size: 24rpx;
      color: var(--text-dark);
    }
  }
}

.options-container {
  margin-bottom: 40rpx;
  min-height: 100rpx;
  
  .option-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 16rpx;
    color: var(--text-light);
    font-size: 28rpx;
    
    .time-picker {
      color: var(--text-light);
      font-size: 28rpx;
      padding: 10rpx 20rpx;
      border: 1rpx solid var(--text-dark);
      border-radius: 8rpx;
      background-color: rgba(255, 255, 255, 0.1);
    }
  }
}

.content-editor {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: var(--paper-bg);
  border-radius: 24rpx;
  padding: 30rpx;
  box-shadow: inset 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .text-area {
    flex: 1;
    width: 100%;
    background-color: transparent;
    border: none;
    resize: none;
    font-size: 32rpx;
    line-height: 1.8;
    color: var(--text-on-paper);
    font-family: 'Kaiti SC', 'STKaiti', 'KaiTi', sans-serif;
    min-height: 400rpx;
    
    &::placeholder {
      color: var(--text-dark);
    }
  }
  
  .char-counter {
    text-align: right;
    font-size: 24rpx;
    color: var(--text-dark);
    margin-top: 20rpx;
  }
}

.success-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: var(--lighter-bg);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 200;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.5s ease;
  
  &.visible {
    opacity: 1;
    pointer-events: all;
  }
  
  text {
    color: var(--accent-gold);
    font-size: 48rpx;
    font-weight: 500;
  }
}
</style> 